﻿using System;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using DreamCube.Framework.DataAccess.Basic;
using DreamCube.Framework.DataAccess.Sqlserver;
using DreamCube.Foundation.Basic.Utility;

namespace DreamCube.DC_52Icon
{
    public partial class details : System.Web.UI.Page
    {
        #region "私有字段"

        /// <summary>
        /// 不同大小的图片Html模板
        /// {0}--表示图片路径（loading图片的url）
        /// {1}--表示图片提示文字
        /// {2}--表示图片宽度
        /// {3}--表示图片高度
        /// {4}--表示图片比例
        /// {5}--图片的超链接
        /// {6}--图片的目标url
        /// {7}--图片的加载失败图片
        /// {8}--图片显示的tips
        /// </summary>
        private static String differentSizeImagesHtml =
            "<div class='alticons' style='margin-top:0px;height:245px;width:186px;'>" +
                "<div class='alticon largersize' id='largersize-256'>" +
                    "<img IsNeedLoad='true' src='{0}' alt='{1}' width='{2}' height='{3}' targetSrc='{6}' errorImgSrc='{7}' />" +
                "</div>" +
                "<p><span>{4} x {4} {8}</span></p>" +
                "<p>{5}</p>" +
            "</div>";

        /// <summary>
        /// {0}--表示图片路径
        /// {1}--表示图片提示文字
        /// </summary>
        private static String imageHrefHtml = "<a rel='nofollow' title='右键另存为' class='downloadlink tip' href='{0}'>{1}</a>";

        /// <summary>
        /// {0}--表示图片路径（loading图片的url）
        /// {1}--表示图片提示文字
        /// {2}--图片的目标url
        /// {3}--图片的加载失败图片
        /// </summary>
        private static String iconHtml = "<img IsNeedLoad='true' id='detail-icon-img' style='vertical-align:middle;' src='{0}' alt='{1}' targetSrc='{2}' errorImgSrc='{3}' />";

        private static String imageServerBasicUrl = ConfigurationManager.AppSettings["imageServerBasicUrl"];

        #endregion

        #region "属性"

        /// <summary>
        /// 图标的关键字
        /// </summary>
        public String KeyWord
        {
            get;
            private set;
        }

        #endregion

        #region "实例方法"

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                LoadIconDetails();
            }
            catch (Exception ex)
            { MyLog.MakeLogAsync(ex); }
        }

        /// <summary>
        /// 加载图标信息
        /// </summary>
        protected void LoadIconDetails()
        {
            String requestID = Request.QueryString["id"];
            Int32 id = -1;
            if (!Int32.TryParse(requestID, out id)) return;
            //增加下载次数
            DoIncreaseDownCount(id);

            DataRow row = GetIconData(id);
            //把图片信息写到页面上
            if (row != null)
            {
                String enKeyWord = row["Keyword"].ToStringEx();
                String zhKeyWord = row["Zhkeyword"].ToStringEx();
                this.icon_down.Text = row["Down"].ToStringEx();
                this.icon_keyword.Text = enKeyWord;
                this.icon_zhkeyword.Text = zhKeyWord;
                KeyWord = enKeyWord + zhKeyWord;
                //创建图片的Html
                CreateIconHtml(row, KeyWord);
                CreateOtherIconHtml(row, KeyWord);
            }
        }

        /// <summary>
        /// 创建点中的图标文件
        /// </summary>
        /// <param name="row"></param>
        protected void CreateIconHtml(DataRow row, String keyword)
        {
            String columnName = "size128";
            if (Convert.ToInt64(row["size128"]) != -1)
                columnName = "size128";
            else if (Convert.ToInt64(row["size64"].ToStringEx()) != -1)
                columnName = "size64";
            else if (Convert.ToInt64(row["size48"].ToStringEx()) != -1)
                columnName = "size48";
            else if (Convert.ToInt64(row["size32"].ToStringEx()) != -1)
                columnName = "size32";
            else if (Convert.ToInt64(row["size24"].ToStringEx()) != -1)
                columnName = "size24";
            else if (Convert.ToInt64(row["size16"].ToStringEx()) != -1)
                columnName = "size16";
            this.icon.Text = iconHtml.FormatEx(
                                            Properties.Resources.loadingImageSrc,
                                            keyword,
                                            imageServerBasicUrl + "?id=" + row[columnName],
                                            Properties.Resources.loadingErrorImage);
        }

        /// <summary>
        /// 创建其他大小的图标文件
        /// </summary>
        /// <param name="row"></param>
        protected void CreateOtherIconHtml(DataRow row, String keyword)
        {
            String[] imageSizes = new String[] { "16", "24", "32", "48", "64", "128", "256" };
            StringBuilder icons = new StringBuilder();
            for (Int32 i = 6; i > -1; i--)
            {
                String pngImageUrl = String.Empty;
                String iconImageUrl = String.Empty;
                if (Convert.ToInt64(row["Size" + imageSizes[i]]) != -1)
                    pngImageUrl = imageServerBasicUrl + "?id=" + row["Size" + imageSizes[i]];
                if (Convert.ToInt64(row["icon" + imageSizes[i]]) != -1)
                    iconImageUrl = imageServerBasicUrl + "?id=" + row["icon" + imageSizes[i]];

                //图片的超链接
                String imageHref = (String.IsNullOrEmpty(pngImageUrl) ? "" : imageHrefHtml.FormatEx(pngImageUrl, "png")) +
                                    (String.IsNullOrEmpty(iconImageUrl) ? "" : imageHrefHtml.FormatEx(iconImageUrl, "ico"));

                /// {0}--表示图片路径（loading图片的url）
                /// {1}--表示图片提示文字
                /// {2}--表示图片宽度
                /// {3}--表示图片高度
                /// {4}--表示图片比例
                /// {5}--图片的超链接
                /// {6}--图片的目标url
                /// {7}--图片的加载失败图片
                if (String.IsNullOrEmpty(imageHref)) continue;
                //当图片大小为256时，需要压小一点显示尺寸
                String imageShowSize = imageSizes[i] == "256" ? "150" : imageSizes[i];
                icons.AppendFormat(differentSizeImagesHtml,
                                    Properties.Resources.loadingImageSrc,
                                    keyword,
                                    imageShowSize,
                                    imageShowSize,
                                    imageSizes[i],
                                    imageHref,
                                    pngImageUrl.IsNullOrEmpty() ? iconImageUrl : pngImageUrl,
                                    Properties.Resources.loadingErrorImage,
                                    imageSizes[i] == "256" ? "<br>(按150*150显示)" : "");
            }
            this.other.Text = icons.ToString();
        }

        #endregion

        #region "静态辅助方法"

        /// <summary>
        /// 根据图标的id号获取图标记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private static DataRow GetIconData(Int32 id)
        {
            String selectSQL = "select * from ICONIndex where code=@code";
            Database db = DbManager.GetDBByName();
            DbCommand selectCommand = db.GetSqlStringCommand(selectSQL);
            db.AddInParameter(selectCommand, "@code", DbType.Int32, id);
            DataTable iconTable = db.ExecuteDataTable(selectCommand);
            if (iconTable != null)
            {
                if (iconTable.Rows.Count > 0)
                    return iconTable.Rows[0];
            }
            return null;
        }

        /// <summary>
        /// 真正做增加图片下载数量的方法
        /// </summary>
        /// <param name="id"></param>
        private static void DoIncreaseDownCount(Int32 id)
        {
            Action a = new Action(() =>
            {
                String updateSQL = "update ICONIndex set down = down + 1 where code=@code";
                Database db = DbManager.GetDBByName();
                DbCommand command = db.GetSqlStringCommand(updateSQL);
                db.AddInParameter(command, "@code", DbType.Int32, id);
                db.ExecuteNonQuery(command);
            });
            a.BeginInvoke(null, null);
        }

        #endregion
    }
}